<template>
  <a-modal :title="title" :width="800" :maskClosable="false" :visible="visible" @cancel="visible = false">
    <a slot="footer">
      <a-button v-if="cancelText" @click="visible = false">{{ cancelText }}</a-button>
      <a-button v-if="okText == '确定'" type="primary" :loading="button_loading" @click="handleSubmit">{{ okText }}</a-button>
      <a-button v-if="okText == '关闭'" type="primary" @click="visible = false">{{ okText }}</a-button>
    </a>
    <a-spin :indicator="indicator" :spinning="spinning" :tip="tip">
      <div class="spin-content">
        <div ref="notclickn" :class="[actionType == 'view' ? 'viewless notclickn' : '']">
          <a-form :form="form" :labelAlign="'left'">
            <a-card size="small" type="inner" :bordered="false" v-if="type != 'simple'">
              <div slot="title" style="text-align:center">
                学生信息
              </div>
              <a slot="extra" href="#" v-if="actionType != 'view'">
                <a-tooltip placement="rightTop" v-if="StudentInfo.name == null">
                  <template slot="title">
                    <span>添加学生</span>
                  </template>
                  <a-button type="primary" @click="$refs.choosemodal.add()" shape="circle" icon="plus" />
                </a-tooltip>
                <a-tooltip placement="rightTop" v-if="StudentInfo.name != null">
                  <template slot="title">
                    <span>修改学生</span>
                  </template>
                  <a-button type="primary" @click="$refs.choosemodal.edit(choosedStudent)" shape="circle" icon="edit" />
                </a-tooltip>
              </a>
              <a-row v-if="StudentInfo.name != null">
                <a-col :sm="24" :md="6" :xl="6">
                  <img v-if="StudentInfo.photoUrl" :src="getImg(StudentInfo.photoUrl)" alt="" style="height:130px;width:100px" />
                </a-col>
                <a-col :sm="24" :md="18" :xl="18">
                  <a-descriptions :column="2">
                    <a-descriptions-item label="姓名">
                      {{ StudentInfo.name }}
                    </a-descriptions-item>
                    <a-descriptions-item label="性别">
                      {{ StudentInfo.sex == 1 ? '男' : '女' }}
                    </a-descriptions-item>
                    <a-descriptions-item label="身份证">
                      {{ StudentInfo.IDNumber }}
                    </a-descriptions-item>
                  </a-descriptions>
                </a-col>
              </a-row>
            </a-card>
            <a-row :gutter="24">
              <a-col :md="12" :sm="24">
                <a-form-item v-bind="formItemLayout" label="申报补助时间">
                  <a-date-picker v-decorator="['declareDate', { rules: [{ required: required, message: '请填写申报时间!' }] }]" style="width: 100%;" :placeholder="actionType == 'view' ? '' : '请选择日期...'" />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item v-bind="formItemLayout" label="申报补助片区">
                  <a-cascader @change="addressChange" :options="options_address" :load-data="loadDataAddress" placeholder="请选择地址..." change-on-select v-decorator="['AddressValue', { rules: [{ required: required, message: '请填写申报补助片区!' }] }]" />
                  <!-- <a-input v-decorator="['declareArea', { rules: [{ required: required, message: '请填写申报补助片区!' }] }]" /> -->
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item v-bind="formItemLayout" label="补助类型">
                  <a-select style="width:100%" allowClear showSearch optionFilterProp="children" :filterOption="filterOption" v-decorator="['subsidyType']">
                    <a-select-option v-for="(item, index) in BZDrop" :key="item.ID" :value="item.ID">
                      {{ item.Title }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
    </a-spin>
    <choose-modal v-if="type != 'simple'" ref="choosemodal" @chooseded="choosed"></choose-modal>
  </a-modal>
</template>

<script>
import { uploadImage, getImg, studentInfo } from '@/api/students'
import { mapActions, mapGetters } from 'vuex'
import ChooseModal from '@/views/StudentsInfo/modules/choosemodal'
import { getDictByCode } from '@/api/dict'
import dropValue from '@/views/dropValue'
import moment from 'moment'
import { areaList } from '@/api/area'
import { dropList } from '@/api/drop'
export default {
  components: { ChooseModal },
  props: {
    actionType: {
      type: String,
      required: true
    },
    display: {
      type: String,
      required: false
    },
    type: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      a: null,
      headers: {
        authorization: 'authorization-text'
      },
      currentId: null,
      required: false,
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      form: this.$form.createForm(this),
      button_loading: false,
      spinning: false,
      tip: null,
      title: '添加申报补助',
      visible: false,
      uploadParams: {
        tablename: 'Budget',
        signname: null
      },
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 9 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 }
        }
      },

      okText: '确定',
      cancelText: '取消',
      choosedStudent: [],
      BZDrop: [],
      options_address: [],
      StudentInfo: {
        photoUrl: null,
        name: null,
        sex: null,
        IDNumber: null
      },
      DeclareArea: null
    }
  },
  watch: {},
  computed: { ...mapGetters(['token']) },
  methods: {
    getImg,
    moment,
    buttonText(actionType) {
      if (actionType == 'view') {
        this.okText = '关闭'
        this.cancelText = null
      } else {
        this.okText = '确定'
        this.cancelText = '取消'
      }
    },
    clearData() {
      Object.assign(this, {
        tip: '数据获取中...',
        StudentInfo: {
          photoUrl: null,
          name: null,
          sex: null,
          IDNumber: null
        }
      })
    },
    choosed(data) {
      this.choosedStudent = data
      if (data.length > 0) {
        studentInfo({ id: data[0].id }).then(res => {
          this.StudentInfo = res.data.StudentInfo
        })
      } else {
        this.StudentInfo = {
          photoUrl: null,
          name: null,
          sex: null,
          IDNumber: null
        }
      }
      this.choosedStudentWatch = data
    },
    closeShareholder(item) {
      this.choosedStudent = this.choosedStudent.filter(a => a.id != item.id)
      this.choosedStudentWatch = this.choosedStudentWatch.filter(a => a.id != item.id)
    },
    add() {
      Object.assign(this, {
        visible: true,
        title: '添加申报补助'
      })
      this.clearData()
      this.form.resetFields()
      setTimeout(() => {
        this.buttonText(this.actionType)
      }, 500)
    },
    edit(data) {
      Object.assign(this, {
        spinning: true,
        visible: true,
        currentId: data.id,
        StudentInfo: data.studentInfo,
        title: '修改申报补助'
      })
      this.form.resetFields()
      this.initData(data)
      this.buttonText(this.actionType)
    },
    view(data) {
      Object.assign(this, {
        spinning: true,
        visible: true,
        currentId: data.id,
        StudentInfo: data.studentInfo,
        title: '查看申报补助'
      })
      this.form.resetFields()
      this.initData(data)
      this.buttonText(this.actionType)
    },
    initData(data) {
      setTimeout(() => {
        this.currentId = data.id
        //#endregion
        const { setFieldsValue } = this.form
        //#region 省市区回填
        var start = new Promise(resolve => {
          setTimeout(() => {
            areaList({ parentID: 0 }).then(res => {
              var _options = []
              res.data.map(a => {
                _options.push({
                  value: a.id,
                  label: a.areaName,
                  isLeaf: false
                })
              })
              this.options_address = _options
            })
          }, 100)
          resolve()
        })
        var firstNative = start.then(() => {
          setTimeout(() => {
            this.loadDataAddress(this.options_address.filter(a => a.value == data.declareArea_province))
            // setFieldsValue({ NativePlaceValue: [StudentInfo.NativePlace_province, StudentInfo.NativePlace_city] })
            // this.NativePlaceValue = [StudentInfo.NativePlace_province, StudentInfo.NativePlace_city]
          }, 500)
        })
        firstNative
          .then(() => {
            console.log(this.options_address)
            return new Promise((resolve, reject) => {
              const b = this.options_address.filter(a => a.value == data.declareArea_province)
              if (b) {
                var params
                const targetOption = b[b.length - 1]
                if (targetOption) {
                  targetOption.loading = true
                  params = b[b.length - 1].value
                  areaList({ parentID: params }).then(res => {
                    var _options = []
                    res.data.map(a => {
                      _options.push({
                        value: a.id,
                        label: a.areaName,
                        isLeaf: a.depth < 2 ? false : true
                      })
                    })
                    targetOption.children = _options
                    targetOption.loading = false
                    this.options_address = [...this.options_address]
                    resolve(this.options_address)
                  })
                }
              }
            })
          })
          .then(options_address => {
            setTimeout(() => {
              const b = options_address.filter(a => a.value == data.declareArea_province)[0]
              if (b) {
                const value = b.hasOwnProperty('children') ? b.children.filter(a => a.value == data.declareArea_city)[0] : null
                var params
                const targetOption = value
                if (targetOption) {
                  targetOption.loading = true
                  params = value.value
                  areaList({ parentID: params }).then(res => {
                    var _options = []
                    res.data.map(a => {
                      _options.push({
                        value: a.id,
                        label: a.areaName,
                        isLeaf: a.depth < 2 ? false : true
                      })
                    })
                    targetOption.children = _options
                    targetOption.loading = false
                    this.options_address = [...options_address]
                    console.log(this.options_address)
                  })
                }
              }
              setFieldsValue({ AddressValue: [data.declareArea_province, data.declareArea_city, data.declareArea_county] })
            }, 500)
          })
        //#endregion

        if (data.declareDate != null) {
          setFieldsValue({ declareDate: moment(data.declareDate, 'YYYY-MM-DD') })
        }
        setFieldsValue({ declareArea: data.declareArea })
        setFieldsValue({ subsidyType: data.subsidyType })
        this.spinning = false
      }, 1000)
    },
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.tranData(values)
        } else {
        }
      })
    },
    tranData(values) {
      var _this = this
      if (this.choosedStudent.length == 0 && this.type != 'simple' && this.StudentInfo.name == null) {
        this.$message.error('未选择学生信息!')
        return
      }
      this.button_loading = true
      setTimeout(() => {
        const value = {
          ...values,
          studentID: this.type != 'simple' ? this.StudentInfo.id : null,
          declareDate: values['declareDate'] == null ? null : values['declareDate'].format('YYYY-MM-DD'),
          declareArea_province: values['AddressValue'].length > 0 ? values['AddressValue'][0] : null,
          declareArea_city: values['AddressValue'].length > 1 ? values['AddressValue'][1] : null,
          declareArea_county: values['AddressValue'].length > 2 ? values['AddressValue'][2] : null,
          DeclareArea: this.DeclareArea,
          addUserID: this.actionType === 'edit' ? null : this.token.id,
          editUserID: this.actionType === 'add' ? null : this.token.id
        }
        this.button_loading = false
        this.$emit('save', value, this.currentId)
        this.visible = false
      }, 1000)
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    setRowClassName(record, idx) {
      return idx % 2 == 1 ? 'bg-zebra-pattern' : ''
    },
    addressChange(value, value2) {
      if (value2.length == 1) {
        this.DeclareArea = value2[0].label
      } else if (value2.length == 2) {
        this.DeclareArea = `${this.DeclareArea}${value2[1].label}`
      } else if (value2.length == 3) {
        this.DeclareArea = `${this.DeclareArea}${value2[2].label}`
      }
    },
    loadDataAddress(value) {
      var params
      const targetOption = value[value.length - 1]
      if (targetOption) {
        targetOption.loading = true
        params = value[value.length - 1].value
        areaList({ parentID: params }).then(res => {
          var _options = []
          res.data.map(a => {
            _options.push({
              value: a.id,
              label: a.areaName,
              isLeaf: a.depth < 2 ? false : true
            })
          })
          targetOption.children = _options
          targetOption.loading = false
          this.options_address = [...this.options_address]
        })
      }
    },
    initAreaList() {
      areaList({ parentID: 0 }).then(res => {
        var _options = []
        res.data.map(a => {
          _options.push({
            value: a.id,
            label: a.areaName,
            isLeaf: false
          })
        })
        this.options_address = _options
      })
    }
  },
  created() {
    dropList({ categoryId: dropValue.BZType }).then(res => {
      this.BZDrop = res
    })
    this.initAreaList()
  },
  mounted() {}
}
</script>
<style lang="less" scoped>
/deep/.ant-card-head {
  color: #ffffff;
  background-color: @primary-color;
}
/deep/.ant-popover-inner-content {
  padding: 0;
}
.ant-form-item {
  margin-bottom: 4px;
}
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}
.ant-upload-list-picture-card-container {
  width: 104px;
  height: 104px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.notclickn {
  pointer-events: none;
}

.viewless {
  /deep/.ant-input-number {
    border: none;
    background: transparent;
  }

  /deep/.ant-input {
    border: none;
    background: transparent;
  }

  .ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  /deep/.ant-input-disabled {
    color: rgba(0, 0, 0, 0.65);
    cursor: default;
  }

  /deep/.ant-select-disabled {
    color: rgba(0, 0, 0, 0.65);
  }

  // /deep/.ant-modal-content {
  //   pointer-events: unset;
  // }
  /deep/.ant-select-selection--single {
    border: none;
    background: transparent;
  }

  /deep/.ant-select-arrow .ant-select-arrow-icon {
    display: none;
  }

  /deep/.anticon {
    display: none;
  }

  /deep/.vue-treeselect div,
  .vue-treeselect span {
    border: none;
  }

  /deep/.vue-treeselect__x-container {
    display: none;
  }

  /deep/.vue-treeselect__control-arrow-container {
    display: none;
  }
}
</style>
